import json
import os

import requests
from zhipuai import ZhipuAI

client = ZhipuAI(api_key=os.environ["ZHIPU_API_KEY"])
weather_api_key = "S3HUcEMMyNbGnqC_g"


def get_weather(city):
    url = f"https://api.seniverse.com/v3/weather/now.json?key={weather_api_key}&location={city}&language=zh-Hans&unit=c"
    response = requests.get(url)
    return response.text

get_weather_description = "这是一个查询某个城市天气的函数"

get_weather_function = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": get_weather_description,
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称"
                }
            },
            "required": ["city"]
        }
    }
}

tools = [get_weather_function]

available_functions = {
    "get_weather": get_weather
}

type_dict = {
    "get_weather": 1
}

while True:
    text = input("请输入：")

    if text == "exit" or text == "quit" or text == "stop" or text == "end" or text == "退出":
        break

    messages = [{"role": "user", "content": text}]
    while True:
        response = client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=messages,
            tools=tools,
            tool_choice="auto"
        )

        if response.choices[0].message.tool_calls != None and len(response.choices[0].message.tool_calls) > 0:

            messages.append(response.choices[0].message.model_dump())
            # 获取函数名称
            function_name = response.choices[0].message.tool_calls[0].function.name
            function_args = json.loads(response.choices[0].message.tool_calls[0].function.arguments)
            functionCallingResult = (available_functions[function_name])(**function_args)
            messages.append({"role": "tool",
                             "content": functionCallingResult,
                             "tool_call_id": response.choices[0].message.tool_calls[0].id})
        else:
            messages.append(response.choices[0].message.model_dump())
            print(response.choices[0].message.content)
            break

print("处理完毕")